﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace photogalleryMVC
{
    public static class HierarchyHelper
    {
       private const int _defaultDepth=2;


       public static string HierarchyNavigation(this HtmlHelper helper, Func<int, string> urlBuilder, Dictionary<int, string> hierarchy, object htmlAttributes)
        {

            return HierarchyNavigation(helper, urlBuilder, hierarchy,_defaultDepth,htmlAttributes  );

        }
        
        public static string HierarchyNavigation(this HtmlHelper helper ,Func<int,string> urlBuilder ,Dictionary< int,string> hierarchy,int depth,object htmlAttributes)
        {
            String result="";

            PropertyInfo[] properties = htmlAttributes.GetType().GetProperties();
            Dictionary<string, string> attributes = new Dictionary<string, string>();
            foreach (var property in properties )
            {
                attributes.Add(property.Name, property.GetValue(htmlAttributes, null).ToString());
            }

            if(depth <1)
                throw new ArgumentOutOfRangeException("depth", " hierarchy depth shuold be >0 ");
            for(int i=0  ;i<hierarchy.Count ; i++)
            {
                
                TagBuilder tag = new TagBuilder("a");
                if(depth >0)
                {
                    KeyValuePair<int, string> element = hierarchy.ElementAt(i);                  
                    tag.MergeAttribute("href", urlBuilder(element.Key) );

                    tag.MergeAttributes(attributes);
                    tag.SetInnerText(element.Value );
                    result = "/"+tag.ToString()  + result;
                    depth --;
                }
                else
                {

                    KeyValuePair<int, string> element = hierarchy.ElementAt(hierarchy .Count -1);                  
                    tag.MergeAttribute("href", urlBuilder(element.Key) );
                    tag.MergeAttributes(attributes);
                    tag.SetInnerText(element.Value );
                    string shortCut = i == hierarchy.Count - 1 ? "" : "/...";
                    result = tag.ToString()  +shortCut + result;
                    return result;
                }
                
                
                
            }
            

            return result;
        }
    }
}